package com.example.demo.filter;


import com.example.demo.entity.LoginUser;
import com.example.demo.utils.JwtUtil;
import com.example.demo.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Description : jwt过滤器
 * @Author : Bruce Lee
 * @CreateTime : 2023/11/29
 */

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 取出请求中携带的token信息；令牌标识可以自定义
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)) {
            // 解析token
            Claims claims = jwtUtil.parserJwt(token);
            // identification本质是用户名
            String identification = (String) claims.get("identification");
            if (StringUtils.hasText(identification)) {
                // token存在
                if (!Objects.isNull(redisUtil.getCacheObject(identification))) {
                    // TODO 强制类型报错: 无法传输对象，传基本类型不会报错
                    LoginUser cacheObject = redisUtil.getCacheObject(identification);

                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(cacheObject, null, cacheObject.getAuthorities());
                    // 每一个请求对应的SecurityContextHolder是不同的
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                } else {
                    throw new NullPointerException("需要重新登录");
                }
            }
        }
        // 放行该请求
        filterChain.doFilter(request, response);
    }
}
